
import { Table, Button, Select, Input, Popconfirm, message, Breadcrumb, Affix } from 'antd';
import { UndoOutlined } from '@ant-design/icons'
// import { getAledataApi } from '@/services/ant-design-pro/api';
import styles from './style.less';
import { Dispatch, useStore,NavLink} from 'umi';
import { useState, useEffect } from 'react';
import ProCard from '@ant-design/pro-card';
import { FC } from 'react';
import { delpathdataApi, allpathApi, allPageApi } from '@/services/ant-design-pro/api';
import { IndexModelState, ConnectProps, Loading, connect } from 'umi';

interface PageProps extends ConnectProps {
  pages: IndexModelState;
  loading: boolean;
  [key: string]: any,
}

const { Option } = Select;
const Index: FC<PageProps> = ({ pagess, initData, filterData }) => {
  const columns = [
    {
      title: '标题',
      width: 100,
      dataIndex: 'name',
      key: 'id',
    },
    {
      title: '路径',
      width: 100,
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '顺序',
      width: 100,
      dataIndex: 'order',
      key: 'order',
    },
    {
      title: '阅读量',
      width: 100,
      dataIndex: 'views',
      key: 'views',

    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'status',
      key: 'status',
      render: (_:any,data:any) => {      
        return  <span>{data.status === 'publish' ? '已发布' : '草稿'}</span>
      }
    },
    {
      title: '发布时间',
      width: 100,
      dataIndex: 'updateAt',
      key: 'updateAt',

    },
    {
      title: '操作',
      key: 'id',
      width: 240,
      render: (_: any, data: any) => {
        console.log(data.status);
        
        return <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <a>编辑</a>
          <a onClick={nowsClom(data)}>{data.status==='publish' ? '下线' : '发布'}</a>
          <a>查看访问</a>
          <Popconfirm title="确认删除？" onConfirm={deldata(data)} okText="删除" cancelText="取消">
            <a>删除</a>
          </Popconfirm>
        </div>
      }
    },
  ]
  // state
  const store = useStore();  
  // 选择
  const [selectedRowKeys, setsel] = useState<any[]>([]);
  // 全选状态
  const [flag, setFlag] = useState(false);
  // 分页
  const [pages, setPage] = useState({ page: 1, pageSize: 6 });
  // 选择数据
  const [status, setSel] = useState('');
  // 选择数据2
  const [path, setSpath] = useState('');
  // 标题搜索数据
  const [name, setIpt] = useState('');
  // 初始化数据
  const datas = store.getState();
  // 全选数据
  const [idarr, setidarr] = useState([]);
  useEffect(() => {
    initData(pages);
  }, [pages]);

  //全选事件
  const onSelectChange = (selectedRowKeys: any) => {
    setsel(selectedRowKeys);
    setidarr(selectedRowKeys);
    // 显示操作
    setFlag(!flag);
  };
  // 全选删除
  const alldel = () => {
    idarr.forEach(async (item) => {
      let res = await delpathdataApi(item);
      if (res.success) {
        initData(pages);
        message.success('删除成功');
      }
    })
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // const hasSelected = selectedRowKeys.length > 0;
  // 设置分页
  const setF = (page: object) => {
    let { current, pageSize } = page as any;
    //拼接
    let obj = { page: current, pageSize };
    setPage(obj);
  }
  // 状态筛选事件
  function handleChange(value: string) {
    setSel(value);
  }
  // 分类筛选事件
  function setPaths(e: any) {
    setSpath(e.target.value);
  }
  // 搜索事件
  function setVal(e: any) {
    setIpt(e.target.value);
  }
  // 搜索
  function search() {
    let obj = { pages, name, status, path };
    filterData(obj);
  }
  // 重置
  function resetData() {
    setSel('');
    setSpath('');
    setIpt('');
    initData(pages);
  }
  // 删除
  const deldata = (data: any) => {
    return async () => {
      await delpathdataApi(data.id);
      initData(pages);
    }
  }
  // 发布-下线 
  const pub = (val: string) => {
    return () => {
      let data = { status: val }
      idarr.forEach(async (item) => {
        let res = await allpathApi(item, data);
        if (res.success) {
          initData(pages);
          message.success(val === 'publish' ? '发布成功' : '操作成功')
        }
      })
    }
  }
  // 单独发布
  const nowsClom = (dataval: any) => {
    return async () => {
      console.log(dataval);
      let data = { status: dataval.status === 'publish' ? 'draft' : 'publish' }
      let res = await allPageApi(dataval.id, data);      
      if (res.success) {
        initData(pages);
        message.success(dataval.status ==='publish' ? '下线成功' : '发布成功');
      }
    }
  }
  const [top,] = useState(40);
  return (
    <div className={styles.ale}>
      <div style={{marginBottom:20}}>
        <Affix offsetTop={top}>
          <ProCard >
            <Breadcrumb>
              <Breadcrumb.Item><NavLink to='/home'>工作台</NavLink></Breadcrumb.Item>
              <Breadcrumb.Item><NavLink to='/page'>页面管理</NavLink></Breadcrumb.Item>
            </Breadcrumb>
          </ProCard>
        </Affix>
      </div>
      {/* 顶部筛选 */}
      <div className={styles.top}>
        <div>
          <label htmlFor="ipt">名称：</label>
          < Input id='ipt' style={{ width: '130px' }} value={name} onChange={setVal} />
        </div>
        <div>
          {/* 分类选择 */}
          <label htmlFor="path">路径：</label>
          < Input id='path' style={{ width: '130px' }} value={path} onChange={setPaths} />
        </div>
        <div>
          <label htmlFor="status">路径：</label>
          {/* 状态选择 */}
          <Select defaultValue={status} id='status' style={{ width: 130 }} onChange={handleChange}>
            <Option value="publish">已发布</Option>
            <Option value="draft">草稿</Option>
          </Select>
        </div>
        {/* 搜索 */}
        <div>
          <Button type="primary" onClick={search}>搜索</Button>
          <Button onClick={resetData}>重置</Button>
        </div>
      </div>
      <div style={{ marginBottom: 16 }} className={styles.show}>
        <div className={styles.left}>
          <div style={{ display: flag ? 'block' : 'none' }}>
            <Button onClick={pub('publish')}>发布</Button>
            <Button onClick={pub('draft')}>下线</Button>
            <Popconfirm title="确认删除？" onConfirm={alldel} okText="删除" cancelText="取消">
              <Button type="primary">删除</Button>
            </Popconfirm>
          </div>
        </div>
        <div>
          <Button type="primary" >新建</Button>
          <span style={{ margin: '0px 20px', display: 'inline-block', cursor: 'pointer' }}><UndoOutlined /></span>
        </div>
      </div>
      <Table style={{ width: '100%' }} rowSelection={rowSelection} onChange={setF} columns={columns as any} rowKey='id' key='id' pagination={{ pageSize: pages.pageSize, total: datas.pages.tol, showSizeChanger: true, pageSizeOptions: ['3', '6', '9'] }} dataSource={datas.pages.data}  />
    </div>
  )
};
const mapState = ({ pages, loading }: { pages: IndexModelState; loading: Loading }) => {
  return {
    pages,
  }
}
const mapDispatch = (dispatch: Dispatch) => {
  return {
    //  初始化数据
    initData(page: any) {
      dispatch({ type: 'pages/query', payload: page })
    },
    // 筛选
    filterData(obj: object) {  
      dispatch({ type: 'pages/filters', payload: { ...obj } });
    },
  }
}
export default connect(mapState, mapDispatch)(Index);